import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ComputerConfigService } from '../../services/computer-config.service';
import { PermissionService } from '../../services/permission.service';
import { ZoneService } from 'app/modules/zone/services/zone.service';

@Component({
  selector: 'm-permission',
  templateUrl: './permission.component.html',
  styleUrls: ['./permission.component.scss'],
})
export class PermissionComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private zone: NgZone,
    private route: ActivatedRoute,
    private router: Router,
    private permissionService: PermissionService,
    private configService: ComputerConfigService,
    private zoneService: ZoneService,
  ) {}

  selectGroupFunc = () =>
    this.fb.group({
      all: [false],
      selected: [[]],
      auth: [true],
    });

  formGroup = this.fb.group({
    id: [0],
    user: this.selectGroupFunc(),
    pc: this.selectGroupFunc(),
    software: this.selectGroupFunc(),
    pc_config: this.configService.computerConfigForm(),
  });

  @ViewChild('form') form: ElementRef<HTMLFormElement>;
  steps = PermissionSteps;
  readonly config_step = 2;

  _current = 0;
  set current(step: number) {
    this._current = step;
    ['user', 'pc'].forEach((name, index) => {
      const value = this.formGroup.get(name).value;
      if (!value.all && !value.selected.length) {
        this.steps[index].invalid = true;
      } else {
        this.steps[index].invalid = false;
      }
    });
  }
  get current() {
    return this._current;
  }
  child = 0;

  clickScrolling = false;

  ngOnInit() {
    this.initDefault();
    // 选择人员后快速定制权限
    const key = this.route.snapshot.queryParamMap.get('key');
    if (key) {
      const value = sessionStorage.getItem(key) || '';
      sessionStorage.removeItem(key);
      const ids = value.split(',').map(Number);
      this.formGroup.get(['user', 'selected']).setValue(ids.map((id) => ({ id })));
    }
  }

  // 一开始就初始化默认配置，避免导航跳过config组件，导致配置为空
  async initDefault() {
    const zoneID = Number(this.route.snapshot.queryParamMap.get('id'));
    const conf = await this.zoneService.getConfig(zoneID);
    const control = this.formGroup.get('pc_config');
    control.patchValue(conf);
  }

  // 终端配置点击导航滚动到节点
  childChange(value: number) {
    if (this.current == this.config_step) {
      setTimeout(() => {
        const cfg = this.form.nativeElement.querySelector('m-config');
        const el = cfg.querySelectorAll(':scope > div').item(value);
        if (el) {
          this.clickScrolling = true;
          el.scrollIntoView();
          setTimeout(() => {
            this.clickScrolling = false;
          }, 100);
        }
      });
    }
  }

  // 终端配置导航滚动
  scroll() {
    if (this.current == this.config_step && !this.clickScrolling) {
      const cfg = this.form.nativeElement.querySelector('m-config');
      const cfgOptions = cfg.querySelectorAll<HTMLDivElement>(':scope > div');
      const last = Array.from(cfgOptions).findIndex((el) => {
        const rect = el.getBoundingClientRect();
        return rect.top >= 0;
      });
      this.zone.runTask(() => {
        this.child = last;
      });
    }
  }

  // 提交定制
  async submit() {
    const zoneID = Number(this.route.snapshot.queryParamMap.get('id'));
    await this.permissionService.submit(zoneID, this.formGroup.value);
    const route = this.route.snapshot;
    this.router.navigate(['/zone', 'detail', route.paramMap.get('name')], {
      queryParams: { id: route.queryParamMap.get('id') },
    });
  }
}

const PermissionSteps = [
  { title: '选择需要定制权限的人员', invalid: false },
  { title: '选择对应的终端', invalid: false },
  // {
  //   title: '对所选终端进行配置调整',
  //   children: ['预览所选内容', '配置屏幕保护', '配置熄屏时间', '配置桌面壁纸', '配置额外脚本'],
  // },
  // { title: '选择对应的软件' },
];
